﻿Imports DotNetNuke.Services.Scheduling
Imports DotNetNuke.Data
Imports System.IO
Imports DotNetNuke.Common
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke
Imports DotNetNuke.Security.Roles
Imports DotNetNuke.Entities.Users
Public Class BlogNotifierScheduler
    Inherits SchedulerClient

    Public Sub New(oItem As ScheduleHistoryItem)
        MyBase.New()
        ScheduleHistoryItem = oItem
    End Sub


    Public Overrides Sub DoWork()
        Try

            Progressing()
            Dim pc As New DotNetNuke.Entities.Portals.PortalController
            Dim portalList As ArrayList = pc.GetPortals()


            For Each p As DotNetNuke.Entities.Portals.PortalInfo In portalList
                Dim notifierSettings As DataTable = DataProvider.Instance().ExecuteDataSet("Blog_Notifier_Get_SettingsByPortal", p.PortalID).Tables(0)

                ScheduleHistoryItem.AddLogNote("Processing Portal: " & "(" & p.PortalID & ") " & p.PortalName & "<br />")

                If notifierSettings.Rows.Count > 0 Then

                    Dim lastEntryId As String = notifierSettings.Rows(0).Item("lastEntryId").ToString
                    Dim notifyRoleId As String = notifierSettings.Rows(0).Item("notifyRoleId").ToString
                    Dim roleName As String = ""
                    Dim emailHtml As String = ""
                    Dim modifiedEmailHtml As String = ""
                    Dim emailSubject As String = ""
                    Dim senderEmail As String = ""
                    Dim sr As StreamReader


                    If lastEntryId = "" Then
                        lastEntryId = -1
                    End If


                    If File.Exists(System.AppDomain.CurrentDomain.BaseDirectory & "DesktopModules/Spiffy/Blog Notifier/email_" & p.PortalID & ".htm") Then
                        sr = File.OpenText(System.AppDomain.CurrentDomain.BaseDirectory & "DesktopModules/Spiffy/Blog Notifier/email_" & p.PortalID & ".htm")
                    Else
                        sr = File.OpenText(System.AppDomain.CurrentDomain.BaseDirectory & "DesktopModules/Spiffy/Blog Notifier/email.htm")
                    End If

                    emailHtml = sr.ReadToEnd
                    sr.Close()
                    sr = Nothing

                    If notifierSettings.Rows(0).Item("SenderEmail").ToString <> "" Then
                        senderEmail = notifierSettings.Rows(0).Item("SenderEmail").ToString
                    Else
                        senderEmail = p.Email
                    End If


                    Dim blogEntries As DataTable = DataProvider.Instance().ExecuteDataSet("Blog_Notifier_Get_Entries", p.PortalID, lastEntryId).Tables(0)

                    If blogEntries.Rows.Count > 0 Then



                        Dim entryId As String = blogEntries.Rows(0).Item("EntryId").ToString
                        Dim title As String = blogEntries.Rows(0).Item("Title").ToString
                        Dim description As String = blogEntries.Rows(0).Item("Description").ToString
                        Dim entryContent As String = blogEntries.Rows(0).Item("Entry").ToString
                        Dim link As String = blogEntries.Rows(0).Item("PermaLink").ToString
                        Dim username As String = blogEntries.Rows(0).Item("Username").ToString
                        Dim displayName As String = blogEntries.Rows(0).Item("DisplayName").ToString

                        If notifierSettings.Rows(0).Item("EmailSubject").ToString <> "" Then
                            emailSubject = notifierSettings.Rows(0).Item("EmailSubject").ToString
                        Else
                            emailSubject = "New Blog Entry: {0}"
                        End If

                        emailSubject = String.Format(emailSubject, title, username, displayName)

                        DataProvider.Instance().ExecuteScalar("Blog_Notifier_Update_EntryId", p.PortalID, entryId)


                        modifiedEmailHtml = emailHtml.Replace("[TITLE]", title)
                        modifiedEmailHtml = modifiedEmailHtml.Replace("[DESCRIPTION]", HttpUtility.HtmlDecode(description))
                        modifiedEmailHtml = modifiedEmailHtml.Replace("[SUMMARY]", HttpUtility.HtmlDecode(description))
                        modifiedEmailHtml = modifiedEmailHtml.Replace("[LINK]", HttpUtility.HtmlEncode(link))
                        modifiedEmailHtml = modifiedEmailHtml.Replace("[ENTRY]", HttpUtility.HtmlDecode(entryContent))
                        modifiedEmailHtml = modifiedEmailHtml.Replace("[USERNAME]", HttpUtility.HtmlDecode(username))
                        modifiedEmailHtml = modifiedEmailHtml.Replace("[DISPLAYNAME]", HttpUtility.HtmlDecode(displayName))

                        Dim rc As New RoleController
                        Dim roles As ArrayList = rc.GetRoles()
                        For Each r As RoleInfo In roles
                            If r.PortalID = p.PortalID And r.RoleID = notifyRoleId Then
                                roleName = r.RoleName
                            End If
                        Next

                        Dim userList As ArrayList = rc.GetUsersByRoleName(p.PortalID, roleName)

                        For Each u As UserInfo In userList
                            DotNetNuke.Services.Mail.Mail.SendMail(senderEmail, u.Email, "", "", Services.Mail.MailPriority.Normal, emailSubject, Services.Mail.MailFormat.Html, Encoding.UTF32, modifiedEmailHtml, "", DotNetNuke.Entities.Host.Host.GetHostSettingsDictionary.Item("SMTPServer"), "", "", "")
                            ScheduleHistoryItem.AddLogNote("&nbsp;&nbsp;Email Sent: " & u.Email & "<br />")
                        Next

                    Else
                        ScheduleHistoryItem.AddLogNote("No new blog entries found" & "<br />")
                    End If

                Else
                    ScheduleHistoryItem.AddLogNote("No Settings found for Portal: " & "(" & p.PortalID & ") " & p.PortalName & "<br />")

                End If

                ScheduleHistoryItem.AddLogNote("Completed Portal: " & "(" & p.PortalID & ") " & p.PortalName & "<br />")


            Next



            ScheduleHistoryItem.Succeeded = True
        Catch ex As Exception
            ScheduleHistoryItem.Succeeded = False
            ScheduleHistoryItem.AddLogNote("Exception= " & ex.ToString())
            Errored(ex)
            DotNetNuke.Services.Exceptions.Exceptions.LogException(ex)
        End Try
    End Sub
End Class
